package com.cuanbo.dualscreenteachfu.matrix;

import com.cuanbo.dualscreenteachfu.base.App;
import com.cuanbo.dualscreenteachfu.constant.MatrixConstant;
import com.cuanbo.dualscreenteachfu.service.BackgroundService;
import com.cuanbo.dualscreenteachfu.utils.BroadcastUtil;
import com.cuanbo.dualscreenteachfu.utils.ConnectStateUtil;
import com.cuanbo.dualscreenteachfu.utils.LogUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;

/**
 * 接收矩阵消息的线程
 */
public class MatrixReceiveThread extends Thread {
    private MatrixInitThread tcpInitThread;
    private InputStream input;
    private String str_receive;
    private boolean loop;

    public MatrixReceiveThread(MatrixInitThread tcpInitThread) {
        this.tcpInitThread = tcpInitThread;
        try {
            input = tcpInitThread.getSocket().getInputStream();
        } catch (IOException e) {}
    }

    @Override
    public void run() {
        super.run();
        loop = true;
        LogUtil.add("接收", "启动接收线程-->" + Thread.currentThread().getName(), "矩阵");
        while (App.running && loop) {
            try {
                //非阻塞接收数据，但数据大小有限制
                byte buffer[] = new byte[10240];
                int count = input.read(buffer);
                if (count != -1) {
                    ConnectStateUtil.recordTime(App.getInstance().getApplicationContext(), MatrixConstant.KEY_MATRIX);
                    str_receive = new String(buffer, 0, count, "utf-8");
                    BroadcastUtil.sendMatrixBroadcast(MatrixConstant.TYPE_MATRIX_RECEIVE_MSG, str_receive);
                }
            } catch (SocketException e) {
                LogUtil.addError(e);
                tcpInitThread.close();
                LogUtil.add("MatrixReceiveThread(168)","matrixTcpInitThread.close()","关闭中控Tcp");
                if (e.getMessage().contains("Socket") && e.getMessage().contains("closed")) {//当socket已关闭时，还做读写操作报该错误
                    //Log.i("MatrixReceiveThread", "当socket已关闭时，还做读写操作报该错误SocketException Socket closed!");
                } else {
                    e.printStackTrace();
                    BackgroundService.reConnectingMatrix = false;
                    BroadcastUtil.sendMatrixBroadcast(MatrixConstant.TYPE_MATRIX_RECEIVE_ERROR);
                }
            } catch (Exception e) {
                LogUtil.addError(e);
                tcpInitThread.close();
                LogUtil.add("MatrixReceiveThread(178)","matrixTcpInitThread.close()","关闭中控Tcp");
                BackgroundService.reConnectingMatrix = false;
                BroadcastUtil.sendMatrixBroadcast(MatrixConstant.TYPE_MATRIX_RECEIVE_ERROR);
                e.printStackTrace();
            }
        }
        try {
            input.close();
        } catch (IOException e) {
        }
        LogUtil.add("接收", "关闭接收线程-->" + Thread.currentThread().getName(), "矩阵");
    }

    public void stopThread() {
        loop = false;
    }
}
